package io.coderyeah.basic.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
    private static final String splitor = ";";

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("# coderyeah的接口测试文档")
                        .description("# coderyeah：18 true")
                        .termsOfServiceUrl("https://coderyeah.gitee.io/")
                        .contact(new Contact("lqs", "https://coderyeah.gitee.io/", "2399690261@qq.com"))
                        .version("1.0")
                        .build())
                //分组名称
                .groupName("petHome:1.0")
                .select()
                //这里指定Controller扫描包路径
                .apis(basePackage("io.coderyeah.org.controller" + splitor + "io.coderyeah.basic.controller"
                        + splitor + "io.coderyeah.user.controller" + splitor + "io.coderyeah.system.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
        return (input) -> {
            for (String packageUrl : basePackage.split(splitor)) {
                ClassUtils.getPackageName(input).startsWith(packageUrl);
            }
            return true;
        };
    }

    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return (input) -> {
            return (Boolean) declaringClass(input).map(handlerPackage(basePackage)).orElse(true);
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.ofNullable(input.declaringClass());
    }
}
